package com.sxkiler.demo.rpc.client;

import com.alibaba.fastjson.JSON;
import com.sxkiler.demo.rpc.model.MessageContext;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 自定义解码器。继承Netty的ByteToMessageDecoder 以提供解码功能
 */
public class MessageDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        byte[] body = new byte[byteBuf.readInt()];//创建一个从readerIndex开始可读取总数的byte数组
        byteBuf.readBytes(body);//将数据读到byte数组当中
        String context = new String(body, StandardCharsets.UTF_8);//转回String
        System.out.println("decoder出来的字符串" + context);
        MessageContext messageContext = JSON.parseObject(context, MessageContext.class);//
        list.add(messageContext);
        byteBuf.skipBytes(byteBuf.readableBytes());
    }
}